package com.qkun.library.utils;

import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;

public class ViewListenerUtils {

    public static void setOnLongClick(@NonNull final View view, final long delayTime,
                                      final View.OnLongClickListener longClickListener) {
        view.setOnTouchListener(new View.OnTouchListener() {

            private final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    if (Utils.nonNull(longClickListener)) {
                        longClickListener.onLongClick(view);
                    }
                }
            };
            private float mX;
            private float mY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        v.removeCallbacks(runnable);
                        mX = event.getX();
                        mY = event.getY();
                        v.postDelayed(runnable, delayTime);
                        break;
                    }
                    case MotionEvent.ACTION_MOVE:
                        if (Math.abs(event.getX() - mX) <= 50 && Math.abs(event.getY() - mY) <= 50)
                            break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        v.removeCallbacks(runnable);
                        break;
                }
                return true;
            }
        });
    }

}
